
var _ = require('lodash'),
    Q = require("q"),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    qcRecordController = require('../../../QC/server/controllers/QCRecord.server.controller'),
    extendEnumController = require('../../../SystemManage/server/controllers/ExtendEnum.server.controller'),
    completePlanController = require('../../../ProduceWork/server/controllers/CompletePlan.server.controllers'),
    enumController = require('../../../QC/server/controllers/Enum.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller');


//获取完工计划
exports.getCompletePlanByDate = function(req, res) {
    var completeDate = req.body.CompleteDate;
    console.log(completeDate);
    var resultData = []
    completePlanController.getCompletePlanByDate(completeDate, function(err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '完工计划查询失败';
                newErr.message = '未找到对应的完工计划！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                for (var i = 0; i < result.length; i++) {
                    var completeQty = 0;
                    var r = result[i];
                    if (r.CompleteQty) {
                        completeQty = r.CompleteQty;
                    } else {
                        completeQty = 0;
                    }
                    resultData.push({
                        _id: r._id,
                        Code: r.Code,
                        LotNumber: r.LotNumber,
                        Qty: r.Qty,
                        CompleteQty: completeQty,
                        QtyRate: completeQty / r.Qty * 100,
                        CompleteTime: r.CompleteTime,
                        ItemMasterCode: r.ItemMaster.Code,
                        Remark: r.Remark,
                    });
                }
                res.json({
                    Data: resultData,
                    Error: null
                });
            }
        }
    });
};

//查询流水良率
exports.queryBizRecordRate = function(req, res) {
    var b = req.body,
        date = b.date,
        workLocation = b.workLocation;

    bizRecordController.queryByDateAndWorkLocation(date, workLocation, function(err, bizRecords) {

        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (bizRecords == null || bizRecords.length === 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询流水记录失败';
            newErr.message = '未找到对应的流水记录！';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        } else {
            //找到不同的ItemMasterCode
            var ItemMasterCodes = [bizRecords[0].BarcodeMaster.ItemMasterCode];
            for (var i = 0; i < bizRecords.length; i++) {
                var repeat = false;
                for (var j = 0; j < ItemMasterCodes.length; j++) {
                    if (bizRecords[i].BarcodeMaster.ItemMasterCode === ItemMasterCodes[j]) {
                        repeat = true;
                        break;
                    }
                }
                if (!repeat) {
                    ItemMasterCodes.push(bizRecords[i].BarcodeMaster.ItemMasterCode);
                }
            }
            //按型号分组
            var items = [];
            var allNum = 0;
            var allQualifiedNum = 0;
            for (var i = 0; i < ItemMasterCodes.length; i++) {
                var num = 0; //统计每型号的总数
                var qualifiedNum = 0; //统计每型号的合格数
                for (var a = 0; a < bizRecords.length; a++) {
                    var tempCode = bizRecords[a].BarcodeMaster.ItemMasterCode;
                    if (ItemMasterCodes[i] === tempCode) {
                        num++;
                        if (bizRecords[a].QCStatus === 0) {
                            qualifiedNum++;

                        }
                    }
                }
                if (num != 0) {
                    items.push({
                        ItemMasterCode: ItemMasterCodes[i],
                        Num: num,
                        QualifiedNum: qualifiedNum,
                        Rate: qualifiedNum / num * 100
                    });
                    allNum += num;
                    allQualifiedNum += qualifiedNum;
                }
            }

            var unbizRecords = [];//不合格品的流水记录
            for (var b = 0; b < bizRecords.length; b++) {
                if(bizRecords[b].QCStatus===0){//合格

                }else{
                    unbizRecords.push(bizRecords[b]);
                }    
            }
            console.log(unbizRecords);
            // console.log("----------------------------------------------");
            if(unbizRecords.length>0){
               //通过不合格品的流水记录，查找品质记录，再查找不良类型，统计不良类型的种类和数量！
                var promises = [];
                var unqcRecords = [];//存入所有不良品的品质记录
                unbizRecords.forEach(function (unbizRecord) {
                    promises.push(queryQCRecord(unbizRecord,unqcRecords));   
                });
                
                Q.all(promises).then(function () {
                    console.log(unqcRecords); 
                    if(unqcRecords.length>0){
                        //找到不同的BadType
                        var BadTypes = [unqcRecords[0].BadType];
                        for (var i = 0; i < unqcRecords.length; i++) {
                            var repeat = false;
                            for (var j = 0; j < BadTypes.length; j++) {
                                if (unqcRecords[i].BadType === BadTypes[j]) {
                                    repeat = true;
                                    break;
                                }
                            }
                            if (!repeat) {
                                BadTypes.push(unqcRecords[i].BadType);
                            }
                        }

                        //按BadType分组
                        var itemBadTypes = [];
                        for (var i = 0; i < BadTypes.length; i++) {   
                            var numBadType = 0;//统计每BadType的总数  
                            for (var a = 0; a < unqcRecords.length; a++) {
                                var tempBadType = unqcRecords[a].BadType;
                                if (BadTypes[i] === tempBadType) {
                                    numBadType++;   
                                }
                            }
                            if (numBadType != 0) {
                                itemBadTypes.push({
                                    BadType: BadTypes[i],
                                    Num: numBadType,
                                    BadTypeName: ''
                                });
                            }
                        }

                        //查找所有的不良类型
                        enumController.findAllExtendEnum("BadType", function (err, result) {
                            if (err) {
                                res.json({
                                    Data: null,
                                    Error: err
                                });
                            }
                            else {
                                if (result == null) {
                                    var newErr = new Error();
                                    newErr.leval = 9;
                                    newErr.title = '查询不良类型失败';
                                    newErr.message = '未找到所有的不良类型！';
                                    res.json({
                                        Data: null,
                                        Error: newErr
                                    });
                                }
                                else {
                                    itemBadTypes.forEach(function (itemBadType) {
                                        for (var i = 0; i < result.Options.length; i++) {
                                            if (result.Options[i].Value === itemBadType.BadType) {
                                                itemBadType.BadTypeName = result.Options[i].Name;           
                                            }
                                        }   
                                    });
                                    res.json({
                                        Data: {
                                          all: {AllNum:allNum,AllQualifiedNum:allQualifiedNum,AllRate:allQualifiedNum/allNum*100},
                                          other: items,
                                          itemBadTypes:itemBadTypes
                                        },
                                        Error: null
                                    });
                                }
                            }
                        });
                    }
                    else{
                        res.json({
                            Data: {
                              all: {AllNum:allNum,AllQualifiedNum:allQualifiedNum,AllRate:allQualifiedNum/allNum*100},
                              other: items,
                              itemBadTypes:[]
                            },
                            Error: null
                        });
                    }
                });  
            } 
            else{
                res.json({
                    Data: {
                      all: {AllNum:allNum,AllQualifiedNum:allQualifiedNum,AllRate:allQualifiedNum/allNum*100},
                      other: items,
                      itemBadTypes:[]
                    },
                    Error: null
                });
            }   
                

 

            // getDayBadTypes(date).then(function(badTypes) {
            //     res.json({
            //         Data: {
            //             all: { AllNum: allNum, AllQualifiedNum: allQualifiedNum, AllRate: allQualifiedNum / allNum * 100 },
            //             other: items,
            //             badTypes: badTypes
            //         },
            //         Error: null
            //     });
            // }, function (err) {
            //     res.json({
            //         Data: null,
            //         Error: err
            //     });
            // });
        }
    });
};

function getDayBadTypes(dayTime) {
    var deferred = Q.defer();

    qcRecordController.getDurationBadTypes(
        new Date(dayTime + " 00:00:00"), new Date(dayTime + " 23:59:59")
    ).then(function(records) {
        if (!records || records.length === 0) {
            deferred.resolve([]);
            return;
        }
        extendEnumController.findEnumOptions('BadType', function(err, option) {
            if (err) {
                deferred.reject(err);
                return;
            }
            var results = [];
            _.forEach(records, function(record) {
                results.push({
                    name: option[record.BadType],
                    value: record.count
                });
            });
            deferred.resolve(results);
        });
    }, function(err) {
        deferred.reject(err);

    });
}

//查找品质记录
function queryQCRecord (unbizRecord,unqcRecords) {
    var deferred = Q.defer();

    qcRecordController.findAllQCRecords(unbizRecord, function (err, results) {
        if (err) {
            deferred.reject(err);
        }
        else {
            if (results) {
                for (var i = 0; i < results.length; i++) {
                    unqcRecords.push(results[i]);
                }
            }
            deferred.resolve(unqcRecords);
        }               
    });

    return deferred.promise;
}
